/*
* Poppy Game Engine - https://pgetemplate.googlecode.com/svn/
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE in PSPSDK root for details.
*
* Copyright (c) 2008 Poppy
*/

#include "stdafx.h"
#include "CTime.h"
#include <list>

namespace PGESystem
{

	class TimerList
	{

	public:

		std::list<LPITIMER*> m_lTimers;
		std::list<LPITIMER*>::iterator m_lTimersIter, m_lTemp;

	};

	CTime::CTime()
	{
		m_bIsInited = false;
		m_pTimerList = 0;
	}

	void CTime::Time()
	{
		assert(m_bIsInited == true);
		PGE_GET_CURRENT_TICK(m_dCurrentTick);
		m_dDeltaTick = m_dCurrentTick - m_dLastTick;
		m_fTimeBeforeLastTime = m_dDeltaTick*m_fChangeRote;
		m_dLastTick = m_dCurrentTick;
		UpdateTimer();
	}

	bool CTime::InitTime( TIME_UNIT unit )
	{
		if(m_bIsInited) return false;
		m_pTimerList = new TimerList();
		PGE_GET_TICK_RESOLUTION(m_dTickResolution);
		if( unit == MSEL ) m_fChangeRote = 1000.0f;
		else if( unit == MICRO ) m_fChangeRote = 1000000.0f;
		else m_fChangeRote = 1.0f;
		m_fChangeRote = m_fChangeRote / m_dTickResolution;
		PGE_GET_CURRENT_TICK(m_dLastTick);
		m_fTimeBeforeLastTime = 0;
		m_eUnit = unit;
		m_bIsInited = true;
		return true;
	}

	void CTime::DestoryTime()
	{
		if(!m_bIsInited) return;
		m_pTimerList->m_lTimersIter = m_pTimerList->m_lTimers.begin();
		for( ; m_pTimerList->m_lTimersIter != m_pTimerList->m_lTimers.end(); m_pTimerList->m_lTimersIter++ )
		{
			SAFE_DELETE(**m_pTimerList->m_lTimersIter);
		}
		SAFE_DELETE(m_pTimerList);
		m_bIsInited = false;
	}

	bool CTime::AddTimer( LPITIMER* timer )
	{
		assert(m_bIsInited == true);
		if(*timer)
		{
			(*timer)->SetDeltaTime(&m_fTimeBeforeLastTime,m_eUnit,&m_dTickResolution,&m_dDeltaTick);
			m_pTimerList->m_lTimers.push_back(timer);
			return true;
		}
		printf("add error!\n");
		return false;
	}

	void CTime::UpdateTimer()
	{
		assert(m_bIsInited == true);
		m_pTimerList->m_lTimersIter = m_pTimerList->m_lTimers.begin();
		for( ; m_pTimerList->m_lTimersIter != m_pTimerList->m_lTimers.end(); m_pTimerList->m_lTimersIter++ )
		{
			if(!(**m_pTimerList->m_lTimersIter))
			{
				m_pTimerList->m_lTemp = m_pTimerList->m_lTimersIter++;
				m_pTimerList->m_lTimers.erase(m_pTimerList->m_lTemp);
				if( m_pTimerList->m_lTimersIter == m_pTimerList->m_lTimers.end() ) break;
			}
			else
			{
				if((**m_pTimerList->m_lTimersIter)->ProcessPerTime())
				{
					SAFE_DELETE(**m_pTimerList->m_lTimersIter);
					m_pTimerList->m_lTemp = m_pTimerList->m_lTimersIter++;
					m_pTimerList->m_lTimers.erase(m_pTimerList->m_lTemp);
					if( m_pTimerList->m_lTimersIter == m_pTimerList->m_lTimers.end() ) break;
				}
			}
		}
	}

}
